<template>
  <div class="cart-container" v-loading="isLoading">
    <!-- 商品分类导航 -->
    <TypeNav :is-show-sort.sync="isShowSort"></TypeNav>
    <div class="cart">
      <h4>全部商品</h4>
      <div class="cart-main">
        <div class="cart-th">
          <div class="cart-th1">全部</div>
          <div class="cart-th2">商品</div>
          <div class="cart-th3">单价（元）</div>
          <div class="cart-th4">数量</div>
          <div class="cart-th5">小计（元）</div>
          <div class="cart-th6">操作</div>
        </div>
        <div class="cart-body">
          <ul class="cart-list" v-for="item in cartList" :key="item.id">
            <li class="cart-list-con1">
              <input
                type="checkbox"
                name="chk_list"
                class="can-click"
                :checked="item.isChecked"
                @change="hanldeSingleCheckBoxClick(item, $event.target)"
              />
            </li>
            <li class="cart-list-con2">
              <img :src="item.imgUrl" />
              <div class="item-msg">
                {{ item.skuName }}
              </div>
            </li>
            <li class="cart-list-con4">
              <span class="price">{{ item.cartPrice || 0 }}</span>
            </li>
            <li class="cart-list-con5">
              <a
                href="javascript:void(0)"
                :class="{ mins: true, 'can-not-click': item.skuNum === 1 }"
                @click="handleCartListChange('reduce', item, $event.target)"
                >-</a
              >
              <input
                autocomplete="off"
                type="text"
                :value="item.skuNum"
                class="itxt"
                @change="handleCartListChange('change', item, $event.target)"
              />
              <a
                href="javascript:void(0)"
                class="plus"
                @click="handleCartListChange('add', item, $event.target)"
                >+</a
              >
            </li>
            <li class="cart-list-con6">
              <span class="sum">{{ item.skuNum * item.cartPrice }}</span>
            </li>
            <li class="cart-list-con7">
              <a class="sindelet" @click.prevent="onDeleteCart(item)">删除</a>
              <br />
              <a href="javascript:viod(0)">移到收藏</a>
            </li>
          </ul>
        </div>
      </div>
      <div class="cart-tool">
        <div class="select-all">
          <input
            class="chooseAll can-click"
            type="checkbox"
            :checked="isAllChecked"
            @change="hanldeAllCheckBoxClick($event.target)"
          />
          <span>全选</span>
        </div>
        <div class="option">
          <a @click="onDeleteSelectShop">删除选中的商品</a>
          <a href="#none">移到我的关注</a>
          <a href="#none">清除下柜商品</a>
        </div>
        <div class="money-box">
          <div class="chosed">已选择 <span>0</span>件商品</div>
          <div class="sumprice">
            <em>总价（不含运费） ：</em>
            <i class="summoney">{{ totalPrice }}元</i>
          </div>
          <div class="sumbtn">
            <a class="sum-btn" @click="$router.push('/trade')">结算</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TypeNav from 'components/common/TypeNav'
import { mapActions, mapGetters, mapMutations } from 'vuex'
import { deleteCartById, changeCheckStatus } from 'api/cart'
import { throttle } from 'lodash'
export default {
  name: 'Cart',
  data () {
    return {
      isShowSort: false,
      // 购物车数量改变肯定要调接口重新渲染,所以只要购物车数量改变就先加载中提示,接口调完再取消加载
      isLoading: false
    }
  },
  props: {},
  components: {
    TypeNav
  },
  computed: {
    ...mapGetters('cart', ['cartList']),
    // 商品的总价格
    totalPrice () {
      // 先把选中的商品过滤出来
      const checkedShop = this.cartList.filter((val) => {
        return val.isChecked === 1
      })
      // 计算总价格
      const totalPrice = checkedShop.reduce((acc, val) => {
        return acc + val.skuPrice * val.skuNum
      }, 0)
      return totalPrice
    },
    // 是否激活全选
    isAllChecked () {
      if (this.cartList.length === 0) {
        return false
      }
      const isAllChecked = this.cartList.every((val) => {
        return val.isChecked === 1
      })
      return isAllChecked
    }
  },
  watch: {},
  created () {
    this.onGetCartList()
  },
  mounted () {},
  methods: {
    ...mapMutations('cart', ['changeCheckedSatus']),
    ...mapActions('cart', ['onGetCartList']),
    ...mapActions('detail', ['onAddCart']),
    // 处理单个复选框选中
    async hanldeSingleCheckBoxClick (item, dom) {
      dom.disabled = true
      // 这个地方注意好逻辑
      const checked = item.isChecked ? 0 : 1
      await changeCheckStatus(item.skuId, checked)
      this.onGetCartList()
      dom.disabled = false
    },
    // 处理所有复选框是否选中
    async hanldeAllCheckBoxClick (dom) {
      // 获取全选的状态,不要获取computed里面 isAllChecked的状态,因为它不是双向绑定的
      const isAllChecked = dom.checked
      let orderCartList = []
      if (isAllChecked) {
        orderCartList = this.cartList.filter((val) => {
          return val.isChecked === 0
        })
      } else {
        orderCartList = this.cartList.filter((val) => {
          return val.isChecked === 1
        })
      }
      this.isLoading = true
      for (const item of orderCartList) {
        const checked = item.isChecked ? 0 : 1
        await changeCheckStatus(item.skuId, checked)
      }
      await this.onGetCartList()
      this.isLoading = false
    },

    handleCartListChange: throttle(async function (type, item, targetDom) {
      if (type === 'reduce' && item.skuNum === 1) {
        return
      }
      this.isLoading = true
      let disNum = 0
      switch (type) {
        case 'add':
          disNum = 1
          break
        case 'reduce':
          item.skuNum < 2 ? (disNum = 0) : (disNum = -1)
          break
        case 'change':
          if (isNaN(targetDom.value) || targetDom.value < 1) {
            disNum = 0
          } else {
            disNum = parseInt(targetDom.value) - item.skuNum
          }
          break
        default:
          break
      }
      // 这里是让用户输入回车后输入框能失焦
      targetDom.blur()
      await this.onAddCart({
        shopId: item.skuId,
        skuNum: disNum
      })
      this.isLoading = false
      this.onGetCartList()
    }, 1000),
    // 删除商品
    async onDeleteCart (item) {
      try {
        await this.$confirm('删除之后不可恢复, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: async (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '删除中...'
              const { data: res } = await deleteCartById(item.skuId)
              instance.confirmButtonLoading = false
              done()
              if (res.code === 200) {
                this.$message.success('删除成功')
                // 重新获取购物车数据
                this.onGetCartList()
              }
            } else {
              done()
            }
          }
        })
      } catch (error) {
        if (error === 'cancel') {
        } else {
          this.$message.error(error.message)
        }
      }
    },
    // 删除选中的商品
    async onDeleteSelectShop () {
      // 没有商品被选择给用户提示
      const hasSelectShop = this.cartList.some((val) => {
        return val.isChecked === 1
      })
      if (!hasSelectShop) {
        return this.$message('您还没有选择任何商品')
      }
      try {
        await this.$confirm('删除之后不可恢复, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: async (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '删除中...'
              const deleteArrId = []
              this.cartList.forEach((val) => {
                if (val.isChecked === 1) {
                  deleteArrId.push(deleteCartById(val.skuId))
                }
              })
              await Promise.all(deleteArrId)
              this.$message.success('删除成功')
              this.onGetCartList()
              instance.confirmButtonLoading = false
              done()
            } else {
              done()
            }
          }
        })
      } catch (error) {
        if (error === 'cancel') {
        } else {
          this.$message.error(error.message)
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
.cart-container {
  .cart {
    width: 1200px;
    margin: 0 auto;
    h4 {
      margin: 9px 0;
      font-size: 14px;
      line-height: 21px;
    }
    .cart-main {
      .cart-th {
        background: #f5f5f5;
        border: 1px solid #ddd;
        padding: 10px;
        overflow: hidden;
        & > div {
          float: left;
        }
        .cart-th1 {
          width: 25%;
          input {
            vertical-align: middle;
          }
          span {
            vertical-align: middle;
          }
        }
        .cart-th2 {
          width: 25%;
        }
        .cart-th3,
        .cart-th4,
        .cart-th5,
        .cart-th6 {
          width: 12.5%;
        }
      }
      .cart-body {
        margin: 15px 0;
        border: 1px solid #ddd;
        .cart-list {
          padding: 10px;
          border-bottom: 1px solid #ddd;
          overflow: hidden;
          & > li {
            float: left;
          }
          .cart-list-con1 {
            width: 15.1%;
          }
          .cart-list-con2 {
            width: 35%;
            img {
              width: 82px;
              height: 82px;
              float: left;
            }
            .item-msg {
              float: left;
              width: 150px;
              margin: 0 10px;
              line-height: 18px;
            }
          }
          // .cart-list-con3 {
          //   width: 9.6%;
          //   .item-txt {
          //     text-align: center;
          //   }
          // }
          .cart-list-con4 {
            width: 9.5%;
          }
          .cart-list-con5 {
            width: 16.4%;
            .mins {
              border: 1px solid #ddd;
              border-right: 0;
              float: left;
              color: #666;
              width: 6px;
              text-align: center;
              padding: 8px;
            }
            input {
              border: 1px solid #ddd;
              width: 40px;
              height: 33px;
              float: left;
              text-align: center;
              font-size: 14px;
            }
            .plus {
              border: 1px solid #ddd;
              border-left: 0;
              float: left;
              color: #666;
              width: 6px;
              text-align: center;
              padding: 8px;
            }
          }
          .cart-list-con6 {
            width: 11.5%;
            .sum {
              font-size: 16px;
            }
          }
          .cart-list-con7 {
            width: 10%;
            a {
              color: #666;
            }
          }
        }
      }
    }
    .cart-tool {
      overflow: hidden;
      border: 1px solid #ddd;
      .select-all {
        padding: 10px;
        overflow: hidden;
        float: left;
        span {
          vertical-align: middle;
        }
        input {
          vertical-align: middle;
        }
      }
      .option {
        padding: 10px;
        overflow: hidden;
        float: left;
        a {
          float: left;
          padding: 0 10px;
          color: #666;
        }
      }
      .money-box {
        float: right;
        .chosed {
          line-height: 26px;
          float: left;
          padding: 0 10px;
        }
        .sumprice {
          width: 200px;
          line-height: 22px;
          float: left;
          padding: 0 10px;
          .summoney {
            color: #c81623;
            font-size: 16px;
          }
        }
        .sumbtn {
          float: right;
          a {
            display: block;
            position: relative;
            width: 96px;
            height: 52px;
            line-height: 52px;
            color: #fff;
            text-align: center;
            font-size: 18px;
            font-family: 'Microsoft YaHei';
            background: #e1251b;
            overflow: hidden;
          }
        }
      }
    }
  }
}
</style>
